//
//  WBHomeController.swift
//  SinaWeibo
//
//  Created by zhuangqianwei on 16/11/12.
//  Copyright © 2016年 zhuangqianwei. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel
private let cellId = "cellId"
private let WbCellId = "WBcellId"
let orginalCell = UINib(nibName: "WBStatusCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! WBStatusCell
let reweetedCell = UINib(nibName: "WBRetweetedStatusCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! WBStatusCell
class WBHomeController: WBBaseTableViewController {

   //视图控制器应该拥有视图模型
    lazy var homeViewModel:WBHomeViewModel = WBHomeViewModel()
    lazy var hmRefreshControl: WBRefreshControl = WBRefreshControl()
    var count = 0
    //设置根视图的大小
     override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !userLogin {
            //设置访客视图的信息
            visitorView.updateInfo(title: "关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
            
         return
        }
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(self.push))
        self.setupTableView()
        //进入页面就开始加载数据
        //控制器只关注状态
       loadData()
    }
    func loadData() {
        
        homeViewModel.loadData(isPullup: indicatorView.isAnimating) { (isSucecess, count) in
            if !isSucecess {
                
                return
            }
            if !self.indicatorView.isAnimating{
            
            self.startAnimtaion(count: count)
                
            }
            //需要停止菊花转动 否则只能加载两次数据：初次和第二次
            self.indicatorView.stopAnimating()
            
            //停止转动
            self.hmRefreshControl.endRefreshing()
            
            self.tableView.reloadData()

        }
    }
    
    //提示显示多少条数据
    private func startAnimtaion(count: Int) {
        //如果正在做动画就直接返回
        if tipLabel.isHidden == false {
            return
        }
        let tipText = count == 0 ? "没有新微博" : "有\(count)条微博"
        //设置文字
        tipLabel.text = tipText
        //1. 在开始动画前显示tipLabel
        self.tipLabel.isHidden = false
        
        //在开始动画之前记录Y值
        let y = self.tipLabel.frame.origin.y
        UIView.animate(withDuration: 1, animations: {
            //2. 做动画 修改Y值
            self.tipLabel.frame.origin.y = navBarHeight
        }, completion:{ (_) -> () in
            //3. 回去的动画  延迟
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.tipLabel.frame.origin.y = y
            }, completion: { (_) -> () in
                self.tipLabel.isHidden = true
            })
        })
    }
//懒加载小菊花
internal lazy var indicatorView: UIActivityIndicatorView = {
    
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    
    
        return indicator
    }()
    
    //实例化提示加载数据的UILabel控件
    private lazy var tipLabel: UILabel = {
        let l = UILabel(title: "", textCololr: UIColor.white, fontSize: 16)
        //设置背景颜色
        l.backgroundColor = UIColor.orange
        //设置隐藏
        l.textAlignment = .center
        l.isHidden = true
        return l
    }()

       private func setupTableView(){
         //没有登录的情况下程序会崩溃  根视图是访客视图,tableView 没有值
        let nib = UINib(nibName: "WBStatusCell", bundle: nil)
        tableView.register(nib, forCellReuseIdentifier: cellId)
        //注册转发微博的cell
        let RetweetNib = UINib(nibName: "WBRetweetedStatusCell", bundle: nil)
        tableView.register(RetweetNib, forCellReuseIdentifier: WbCellId)
        
        tableView.separatorStyle = .none
        tableView.tableFooterView = indicatorView
        //直接给refreshControl实例化就可以用
//        refreshControl = UIRefreshControl()
        //监听事件类型
        hmRefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        self.view.addSubview(hmRefreshControl)
        //添加tipLabel
        tipLabel.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 35)
        //self.view.addSubview(tipLabel)
        //添加导航视图控制器的根视图上
        //设置Y值
        tipLabel.frame.origin.y = navBarHeight - 35
        //self.navigationController?.view.addSubview(tipLabel)
        //移动到导航条下面
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)
    }
  
    

  @objc private func push() {
        
        self.navigationController?.pushViewController(WBDemoViewController(), animated: true)
        
        
    }

    
    
    // MARK: - Table view data source

    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                return self.homeViewModel.viewModelArray.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //根据viewModel判断使用哪个cellId
        let viewModel = self.homeViewModel.viewModelArray[indexPath.row]
        let cellID = getCellId(viewModel: viewModel)
       let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as!WBStatusCell
        cell.viewModel = viewModel

        return cell
    }
    //系统会先调用获取行高的协议方法
    //先调用获取行高的协议方法
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //获取cell
        count = count + 1
        
        let viewmodel = self.homeViewModel.viewModelArray[indexPath.row]
        
        return viewmodel.rowHeight

        }

    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //如果显示的是倒数第二个cell，并且菊花没有转动的时候，就开始执行静默加载
        if indicatorView.isAnimating == false && indexPath.row == self.homeViewModel.viewModelArray.count - 2 {
            
            indicatorView.startAnimating()
            print("😊😄")
            //请求更多数据
            loadData()
        }
        
    }

    //根据数据获取可重用标识id
    private func getCellId(viewModel: WBStatusViewModel) -> String {
        
        
        return viewModel.status?.retweeted_status == nil ? cellId : WbCellId
        
    }

   
}
